package com.lf.sys.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;

public class MailSender {
	private Properties properties;
	private Session session;
	private MailBean mailBean;
	private int state = 0;
	private String errorMsg;

	public MailSender(MailBean mailBean) {
		this.mailBean = mailBean;
	}

	public MimeMessage SendEmail(String to, String copyTo,String bCopyTo,String subject, String content, String[] files, boolean priority,
			boolean notification) {
		this.init();
		if (this.state != 0) {
			return null;
		}
		// SysMessageSend send = null;
		Date date = new Date();
		MimeMessage message = new MimeMessage(this.session);
		try {
			if (priority) {
				message.setHeader("X-Priority", "1");
			}
			if (notification) {
				message.setHeader("Disposition-Notification-To", this.mailBean.getAccount());
			}
			message.setFrom(new InternetAddress(this.mailBean.getAccount()));
			message.setRecipients(MimeMessage.RecipientType.TO, to);
			message.setRecipients(MimeMessage.RecipientType.CC, copyTo);
			message.setRecipients(MimeMessage.RecipientType.BCC, bCopyTo);
			message.setSubject(subject, "UTF-8");
			message.setSentDate(date);
			// 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			// 添加邮件正文
			BodyPart contentPart = new MimeBodyPart();
			contentPart.setContent(content, "text/html;charset=UTF-8");
			multipart.addBodyPart(contentPart);
			// 添加附件的内容
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					try {
						File file = new File(files[i]);
						BodyPart attachmentBodyPart = new MimeBodyPart();
						DataSource source = new FileDataSource(file);
						attachmentBodyPart.setDataHandler(new DataHandler(source));
						// MimeUtility.encodeWord可以避免文件名乱码
						attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
						multipart.addBodyPart(attachmentBodyPart);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			message.setContent(multipart);
			message.saveChanges();

		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.state = 1;
			this.errorMsg = e.getMessage();
		}
		try {
			Transport transport = session.getTransport("smtp");
			transport.connect(this.mailBean.getHost(), this.mailBean.getAccount(), this.mailBean.getPassword());
			transport.sendMessage(message, message.getAllRecipients());
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.state = 1;
			this.errorMsg = e.getMessage();

		}
		return message;

	}
	
	
	public MimeMessage replyMail(Message org, String to, String copyTo, String bCopyTo, String subject, String content,
			String[] files, boolean priority, boolean notification,boolean replyAll) {
		this.init();
		if (this.state != 0) {
			return null;
		}
		MimeMessage replyMessage = null;
		Date date = new Date();
		try {
			replyMessage = (MimeMessage) org.reply(replyAll);
			replyMessage.setFrom(this.mailBean.getAccount());
			replyMessage.setReplyTo(org.getReplyTo());
			
			System.out.println(org.getReplyTo().length);
			
			replyMessage.setRecipients(MimeMessage.RecipientType.TO, to);
			replyMessage.setRecipients(MimeMessage.RecipientType.CC, copyTo);
			replyMessage.setRecipients(MimeMessage.RecipientType.BCC, bCopyTo);
			replyMessage.setSubject(subject, "UTF-8");
			replyMessage.setSentDate(date);
			if (priority) {
				replyMessage.setHeader("X-Priority", "1");
			}
			if (notification) {
				replyMessage.setHeader("Disposition-Notification-To", this.mailBean.getAccount());
			}
			// 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			// 添加邮件正文
			BodyPart contentPart = new MimeBodyPart();
			contentPart.setContent(content, "text/html;charset=UTF-8");
			multipart.addBodyPart(contentPart);
			// 添加附件的内容
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					try {
						File file = new File(files[i]);
						BodyPart attachmentBodyPart = new MimeBodyPart();
						DataSource source = new FileDataSource(file);
						attachmentBodyPart.setDataHandler(new DataHandler(source));
						// MimeUtility.encodeWord可以避免文件名乱码
						attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
						multipart.addBodyPart(attachmentBodyPart);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			replyMessage.setContent(multipart);
			replyMessage.saveChanges();
			Transport transport = session.getTransport("smtp");
			transport.connect(this.mailBean.getHost(), this.mailBean.getAccount(), this.mailBean.getPassword());
			transport.sendMessage(replyMessage, replyMessage.getAllRecipients());
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return replyMessage;
	}

	/**
	 * 初始化，状态写在state中
	 */
	public void init() {
		if (this.mailBean == null) {
			this.state = 1;
			this.errorMsg = "MAILBEAN_EMPTY";
			return;
		}
		// 设置properties开始
		this.properties = System.getProperties();
		if (StringUtils.isNotBlank(this.mailBean.getHostProp()) && StringUtils.isNotBlank(this.mailBean.getHost())) {
			this.properties.setProperty(this.mailBean.getHostProp(), this.mailBean.getHost());
		}
		if (StringUtils.isNotBlank(this.mailBean.getPortProp()) && StringUtils.isNotBlank(this.mailBean.getPort())) {
			this.properties.setProperty(this.mailBean.getPortProp(), this.mailBean.getPort());
		}
		if (StringUtils.isNotBlank(this.mailBean.getProtocolProp())
				&& StringUtils.isNotBlank(this.mailBean.getProtocol())) {
			this.properties.setProperty(this.mailBean.getProtocolProp(), this.mailBean.getProtocol());
		}

		if (this.mailBean.isSSL()) {
			if (StringUtils.isNotBlank(this.mailBean.getAuthProp())
					&& StringUtils.isNotBlank(this.mailBean.getAuth())) {
				this.properties.setProperty(this.mailBean.getAuthProp(), this.mailBean.getAuth());
			}
			if (StringUtils.isNotBlank(this.mailBean.getSocketFactoryClassProp())
					&& StringUtils.isNotBlank(this.mailBean.getSocketFactoryClass())) {
				this.properties.setProperty(this.mailBean.getSocketFactoryClassProp(),
						this.mailBean.getSocketFactoryClass());
			}
			if (StringUtils.isNotBlank(this.mailBean.getSocketFactoryFallbackProp())
					&& StringUtils.isNotBlank(this.mailBean.getSocketFactoryFallback())) {
				this.properties.setProperty(this.mailBean.getSocketFactoryFallbackProp(),
						this.mailBean.getSocketFactoryFallback());
			}
			if (StringUtils.isNotBlank(this.mailBean.getSocketFactoryPortProp())
					&& StringUtils.isNotBlank(this.mailBean.getSocketFactoryPort())) {
				this.properties.setProperty(this.mailBean.getSocketFactoryPortProp(),
						this.mailBean.getSocketFactoryPort());
			}

		}
		if (this.mailBean.isSSL()) {
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		}
		// 设置properties结束
		// 获取连接
		this.session = Session.getInstance(properties);
		this.session.setDebug(false);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	public MailBean getMailBean() {
		return mailBean;
	}

	public void setMailBean(MailBean mailBean) {
		this.mailBean = mailBean;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

}
